<template>
    <div class="audioplay">
        <audio
         id="player" 
         :src="audioStore.url"
          controls 
          preload="auto"
           @canplay="startPlay" 
           @ended="ended"
           @timeupdate="timeupdate">
        </audio>
    </div>
</template>

<script setup name="audioPlay">
import { watch } from 'vue';
import { useAudioStore } from '@/store/audio';
const audioStore = useAudioStore()

watch(()=>audioStore.isPlay, () => {
    togglePlay();
});

watch(()=>audioStore.changeTime,()=>{
    let player = document.querySelector('#player')
    player.currentTime = audioStore.changeTime
})
watch(()=>audioStore.volume,(val)=>{
    let player = document.querySelector('#player')
    player.volume = val
})

// 获取链接后准备播放
function startPlay() {
    let player = document.querySelector('#player')
    audioStore.duration = player.duration
    audioStore.isPlay = true
    player.play()
}
function ended() {
    audioStore.isPlay = false
    audioStore.curTime = 0
    audioStore.autoNext= !audioStore.autoNext
}
function togglePlay() {
    let player = document.querySelector('#player'); 
    if (!player) {
        console.error('播放器元素未找到');
        return;
    }
    try {
        if (audioStore.isPlay) {
            player.play();
        } else {
            player.pause();
        }
    } catch (error) {
        console.error('播放或暂停操作失败:', error);
    }
}
function timeupdate(){
    let player = document.querySelector('#player');
    audioStore.curTime = player.currentTime
}

</script>

<style scoped>
.auidoplay {
    display: none;
}
</style>
